//
//  PlayViewController.m
//  penzer
//
//  Created by caiyc on 2018/9/18.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "C_PlayViewController.h"
#import <BDCloudMediaPlayer/BDCloudMediaPlayerController.h>
//#import <BDCloudAVBidirectRTMPKit/BDCloudAVBidirectRTMPSession.h>
#import "Regist2ViewController.h"
#import "NoRewardViewController.h"
#import "RewardViewController.h"
#import "WXApi.h"
#import "Result_popView.h"
#import "Exam_popView.h"
#import "pop_func.h"
#import "pop_goodView.h"
#import "DXAlertView.h"
#import "DanmuCell.h"
#import "TYFWaveButton.h"
#import "WZFlashButton.h"
#import "WaveView.h"
#import "HostDetailViewController.h"
#import "SRWebSocket.h"
#import "ReportViewController.h"
#import "C_SocketUtility.h"
#import "JFRWebSocket.h"
#import "LWShareService.h"
@interface C_PlayViewController ()<UITableViewDataSource,UITableViewDelegate,PopfunsDelegate,UITextFieldDelegate,DXAlertViewDelegate,examPopDelegate,ResultPopDelegate,JFRWebSocketDelegate>
@property(nonatomic,strong)BDCloudMediaPlayerController *player;
@property(assign)NSInteger rewad_Num;//本场活动的中奖数字111111444444
@property(assign)NSInteger right_Answer;//知识竞赛的正确答案
@property(assign)NSInteger cutdown_time;//抢购开始的时间
@property(assign)NSInteger end_time;//活动结束时间
@property(nonatomic,strong)UILabel *time_lab1;
@property(nonatomic,strong)UILabel *time_lab2;
@property(nonatomic,strong)UILabel *time_lab3;
@property(nonatomic,strong)UILabel *time_lab4;
@property(nonatomic,strong)UIImageView *like_image;
@property(nonatomic,strong)UIButton *random_Btn;
@property(nonatomic,strong)UIImageView *randImg;
@property(nonatomic,strong)NSTimer *rand_Timer;
@property (nonatomic ,strong)dispatch_source_t timer;
@property (nonatomic ,strong)dispatch_source_t timer1;//管理开启互动的倒计时
@property(assign)NSInteger totalDaotime;//互动开启的倒计时时间
@property(assign)BOOL isrobing;//是否已经在抢购
@property(nonatomic,strong)UIView *result_view;
@property(nonatomic,strong)MBProgressHUD *HUD;
@property(nonatomic,strong)NSString *playUrl;
@property(nonatomic,strong)NSString *prize_token;//中奖人的token
@property(nonatomic,strong)NSDictionary *live_Detail;//直播详情数据
@property(nonatomic,strong)NSDictionary *prize_Info;//中奖信息
@property(nonatomic,strong)UITableView *left_tab;//左侧tablveView
@property(nonatomic,strong)NSMutableArray *newsComent;
@property(nonatomic,strong)UIView *hostInfoView;//主播信息的视图
@property(nonatomic,strong)UIView *danmuTextView;//s发弹幕的弹出视图
@property(nonatomic,strong)UITextField *sendDanmutext;
@property(assign)NSInteger Dampage;
@property (nonatomic ,strong)dispatch_source_t Dm_timer;
@property(assign)BOOL openDm;
@property(nonatomic,strong)NSArray *color_Arr;
@property(assign)BOOL collectStatus;
@property(assign)BOOL activeStart;
@property(assign)NSInteger game_type;//游戏类型
@property(nonatomic,strong)CALayer *moveLayer;
@property(nonatomic,strong)UIView *lift_View;//
@property(assign)BOOL isclick;//是否点中礼物
@property(nonatomic,strong)UITapGestureRecognizer *clickred;
@property(assign)BOOL isfans;//是否关注
@property(nonatomic,strong)UILabel *dayLb;
//@property(nonatomic,strong)SRWebSocket *socket;
@property(nonatomic,strong)JFRWebSocket *socket;
@property(nonatomic,strong)NSDictionary *shareData;
@property(assign)NSInteger countHeart;
@property(nonatomic,strong)UIView *endpopView;
@property(nonatomic,strong)UILabel *activeOutLab;
@property(assign)BOOL isactiveing;//是否向服务器发送请求互动的指令
#define margin_left 10
#define time_Lab_width 20
#define time_Lab_height 25
#define pageSize 1

@end

@implementation C_PlayViewController
#pragma mark 控制器初始化
-(void)dealloc{}
-(void)viewWillAppear:(BOOL)animated{
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSomeFunc];
    [self ShareData];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
#pragma mark 初始化一些东西
-(void)initSomeFunc{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refersh) name:@"enterforhead" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHiden:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeExit:)
                                                 name:UIApplicationWillResignActiveNotification object:nil]; //监听是否触发home键挂起程序.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeExit:)
                                                 name:@"enterback" object:nil]; //监听是否触发home键挂起程序.
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playStop:) name:BDCloudMediaPlayerPlaybackDidFinishReasonUserInfoKey object:nil];
    UITapGestureRecognizer *tapview = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKb)];
    [self.view addGestureRecognizer:tapview];
    [self loadUserInfo];
    [self loadliveInfo];
    
    [self loadLikeNum];
    self.openDm = 1;
    self.collectStatus = 1;
    self.Dampage = 1;
}
#pragma mark 数据交互
-(void)loadUserInfo{
    NSDictionary *params = @{@"ctrl":@"live",@"ac":@"member",@"op":@"member",@"ta":@"get_member"};
    [self weqPostHandle:params success:^(id response) {
        if(response){
            NSDictionary *dic =[NSDictionary changeType: response[@"data"]];
            [XTool SaveDefaultInfo:dic Key:USER_INFO];
           // self.nect_Lvecel.text = [NSString stringWithFormat:@"还差%@经验值升级",response[@"data"][@"next_level"]];
        }
    } failure:^(NSError *error) {
        
    }];
}
//绑定主播信息
-(void)bindHostInfo{
    [self.player.view addSubview:self.hostInfoView];
    for(UIView *view in [self.hostInfoView subviews]){
        [view removeFromSuperview];
    }
    //is_collect
    UIImageView *host_Icon = [[UIImageView alloc] init];
    host_Icon.frame = CGRectMake(0,0,40,40);
    host_Icon.contentMode = UIViewContentModeScaleAspectFill;
    host_Icon.layer.cornerRadius = 20;
    host_Icon.layer.masksToBounds = 1;
    NSDictionary *hostInfo = self.live_Detail[@"anchor_list"][0];
    NSURL *host_icons = [NSURL URLWithString:self.live_Detail[@"anchor_list"][0][@"avatar"]];
    [host_Icon sd_setImageWithURL:host_icons placeholderImage:[UIImage imageNamed:@"logo"]];
    // host_Icon.image = [UIImage imageNamed:@"hosts"];
    [_hostInfoView addSubview:host_Icon];
    
    
    NSString *nick_Str = hostInfo[@"nickname"];
    CGFloat widths  =[XTool calculateRowWidth:nick_Str andHeight:15 andSize:12];
    if(widths>70){
        widths =70;
    }
    UILabel *nick_Lab = [[UILabel alloc] init];
    nick_Lab.frame = CGRectMake(45,5,widths,15);
    nick_Lab.text = hostInfo[@"nickname"];
    nick_Lab.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:12];
    nick_Lab.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
    nick_Lab.textAlignment = NSTextAlignmentLeft;
    nick_Lab.alpha = 1;
    nick_Lab.numberOfLines = 0;
    [_hostInfoView addSubview:nick_Lab];
    
    UIImageView *level_Img = [[UIImageView alloc]initWithFrame:CGRectMake(45+5+widths, 5, 25, 13)];
    level_Img.image = [UIImage imageNamed:@"Group 20"];
    // level_Img.contentMode = UIViewContentModeScaleAspectFit;
    [_hostInfoView addSubview:level_Img];
    
    UILabel *leve_Lab = [[UILabel alloc]initWithFrame:CGRectMake(45+10+widths, 5, 20, 13)];
    leve_Lab.text = @"1";
    leve_Lab.textAlignment = NSTextAlignmentCenter;
    leve_Lab.textColor=[UIColor whiteColor];
    leve_Lab.font = [UIFont systemFontOfSize:11];
   // leve_Lab.textAlignment = NSTextAlignmentRight;
    [_hostInfoView addSubview:leve_Lab];
    
    UILabel *room_id = [[UILabel alloc] init];
    room_id.frame = CGRectMake(45,20,140,20);
    room_id.text = [NSString stringWithFormat:@"房间号：%@ ",self.live_Detail[@"store"][@"room_number"]];
    
    room_id.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:11];
    room_id.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
    room_id.textAlignment = NSTextAlignmentLeft;
    room_id.alpha = 1;
    room_id.numberOfLines = 0;
    [_hostInfoView addSubview:room_id];
    
    UIButton*collect = [UIButton buttonWithType:UIButtonTypeCustom];
    collect.frame = CGRectMake(176-40, 10, 40, 30);
  
    [collect setImage:[UIImage imageNamed:@"collectsno"] forState:UIControlStateNormal];
    [collect setImage:[UIImage imageNamed:@"collectsel"] forState:UIControlStateSelected];
    if(self.isfans==0){
        collect.selected = 0;
    }else{
        collect.selected = 1;
    }
    [collect addTarget:self action:@selector(focus:) forControlEvents:UIControlEventTouchUpInside];
    [_hostInfoView addSubview:collect];
    
    UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    selectBtn.frame = CGRectMake(0, 0, 176-50, 40);
    [selectBtn addTarget:self action:@selector(checkHost) forControlEvents:UIControlEventTouchUpInside];
    [_hostInfoView addSubview:selectBtn];
}
#pragma mark 查看主播信息
-(void)checkHost{
    HostDetailViewController *vc = [[HostDetailViewController alloc]init];
    vc.hostid = self.live_Detail[@"anchor_list"][0][@"anchor_id"];
    [self pushSecondVC:vc];
}
-(UIView *)hostInfoView{
    if(!_hostInfoView){
        NSInteger margin_Top = KISIphoneX?55:30;
        //顶部主播简介
        _hostInfoView = [[UIView alloc] init];
        _hostInfoView.frame = CGRectMake(17.5, margin_Top,176,40);
        _hostInfoView.layer.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.6].CGColor;
        _hostInfoView.layer.cornerRadius = 20;
    }
    return _hostInfoView;
}
-(NSMutableArray *)newsComent{
    if(!_newsComent){
        _newsComent = [NSMutableArray array];
    }
    return _newsComent;
}
#pragma mark 发送弹幕
-(void)senDamu{
    [self.view endEditing:1];
    self.danmuTextView.frame = CGRectMake(10, 10000, screen_width-20, 50);
    if([self.sendDanmutext.text isEqualToString:@""]){
        [WToast showWithText:@"请输入"];
        return;
    }
    NSDictionary *dic = @{@"group_logo":[XTool GetDefaultInfo:USER_INFO][@"group_logo"],@"group_color":[XTool GetDefaultInfo:USER_INFO][@"group_color"], @"mes":self.sendDanmutext.text,@"user_name":[XTool GetDefaultInfo:USER_INFO][@"nickname"],@"room_no":self.roomNum,@"aid":self.live_id,@"uid":[XTool GetDefaultInfo:USER_INFO][@"id"],@"sid":self.live_Detail[@"sid"],@"anchor_id":self.live_Detail[@"anchor_list"][0][@"anchor_id"],@"groupid":[XTool GetDefaultInfo:USER_INFO][@"groupid"]};
    NSString *jsons = [self dictiontoJson:dic andCode:2];
    [self.socket writeString:jsons];
    // [_socket send:jsons];
    self.sendDanmutext.text = @"";
}

#pragma mark 互动倒计时时间
-(void)showActiveTimeout{

    [self activeOutLab];
    self.activeOutLab.hidden= 0;
    NSLog(@"....%ld",self.totalDaotime);
   // self.totalDaotime = 3;
     self.activeOutLab.text = [NSString stringWithFormat:@"%ld",self.totalDaotime];
    self.totalDaotime--;
    [UIView animateWithDuration:0.5 animations:^{
       self.activeOutLab.font = [UIFont systemFontOfSize:200];
    }];
}
#pragma mark 弹出答题的j窗口
-(void)showExamp{
    NSDictionary *diction= self.live_Detail[@"game"][0];
    Exam_popView *exam = [[Exam_popView alloc]initWithexamdata:diction];
    exam.delegate = self;
    [exam show];
}
#pragma mark 输入框回调事件
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
}
#pragma mark 左边滚动视图代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.newsComent.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"cell";
    DanmuCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell){
        cell =[[[NSBundle mainBundle]loadNibNamed:@"DanmuCell" owner:self options:nil]lastObject];
    }
    Danmu_Model *model  = self.newsComent[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSString *danmu = model.content;
    CGFloat widthss = 0;
    if(model.type==0){
    widthss= [XTool calculateRowWidth:danmu andHeight:26 andSize:13];
    }else{
        danmu = [NSString stringWithFormat:@"%@ %@",model.userName,model.content];
        widthss = [XTool calculateRowWidth:danmu andHeight:26 andSize:13]+35;
    }

    cell.contentView.transform=CGAffineTransformMakeScale(1, -1);
    if(model.type==0){
        cell.DanmuText.text = danmu;
        cell.back_Lable.text = danmu;
    }else{
        cell.DanmuText.attributedText = model.contentAttr;
        cell.back_Lable.text = model.contentAttr.string;
    }
    [cell layoutIfNeeded];

    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}
-(void)showDam{
    
    // [self.sendDanmutext becomeFirstResponder];
}
#pragma mark 弹幕评论框长度限制
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    
//    if (textField == self.sendDanmutext) {
//        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
//        if (range.length == 1 && string.length == 0) {
//            return YES;
//        }
//        //so easy
//        else if (self.sendDanmutext.text.length >= 20) {
//            self.sendDanmutext.text = [textField.text substringToIndex:20];
//            return NO;
//        }
//    }
//    return YES;
//}
#pragma mark 界面元素

#pragma mark 中途退出直播间之后进入
-(void)refersh{
    if(self.player){
        //如果有播放器类
        [self.player stop];
        for(UIView *view in [self.player.view subviews]){
            [view removeFromSuperview];
        }
        [self.player.view removeFromSuperview];
        
        self.left_tab = nil;
        [self.newsComent removeAllObjects];
    }
    if(self.danmuTextView!=nil)
    {
        [self.danmuTextView removeFromSuperview];
        self.danmuTextView = nil;
        self.sendDanmutext = nil;
    }
    if(self.timer){
        //如果有计时器，先取消，后重置
        dispatch_cancel(self.timer);
        self.timer = nil;
    }
[self loadliveInfo];
   
    
}
#pragma mark 计时器
//暂停定时器(只是暂停,并没有销毁timer)
-(void)pauseTimer{
    [self.rand_Timer setFireDate:[NSDate distantFuture]];
}
//继续计时
-(void)continueTimer{
    [self.rand_Timer setFireDate:[NSDate distantPast]];
}

//开始随机
-(void)startimer{
    [self.view bringSubviewToFront:self.random_Btn];
    self.random_Btn.hidden = 0;
    self.randImg.hidden = 0;
    [self.rand_Timer fire];
}
//暂停并销毁
-(void)stopTimer{
    self.random_Btn.hidden = 1;
    self.randImg.hidden = 1;
    [self.rand_Timer invalidate];
    self.rand_Timer = nil;
}
-(NSTimer*)rand_Timer{
    if (!_rand_Timer) {
        _rand_Timer =[NSTimer scheduledTimerWithTimeInterval:0.1  target:self  selector:@selector(randoms) userInfo:nil  repeats:YES];
    }
    return _rand_Timer;
}

#pragma mark 连接socket
-(void)connectHost{

    NSDictionary *dic = [XTool GetDefaultInfo:USER_INFO];
    NSString *str = [NSString stringWithFormat:@"scene=room&room_no=%@&token=%@&username=%@&u_type=1",self.roomNum,dic[@"token"],dic[@"nickname"]];
    if(self.socket){
        [self.socket disconnect];
    }
    NSString *strs = [NSString stringWithFormat:@"%@:%@?%@",SOCKET_HOST,SOCKET_PORT,str];
    NSString *encodedValue = [strs stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.socket = [[JFRWebSocket alloc] initWithURL:[NSURL URLWithString:encodedValue] protocols:@[@"chat",@"superchat"]];
    self.socket.delegate = self;
    [self.socket connect];
  
}
#pragma mark socket代理
-(void)websocketDidConnect:(JFRWebSocket*)socket {
    NSLog(@"开启成功");
    NSInteger times = [self.live_Detail[@"current_endtime"]integerValue]-[self.live_Detail[@"service_time"]integerValue];
    if(times>0){
        //已经在抢购中//延时2s发送互动开始的通知
        self.isactiveing = 1;
        [self performSelector:@selector(sendActiveNoti) withObject:nil afterDelay:2];
       
    }
}
-(void)sendActiveNoti{
    NSDictionary *param = @{@"id":self.live_id,
                            @"u_type":@"1",
                            @"room_no":self.roomNum,
                            @"types":@"1"};
    NSString *str = [self dictiontoJson:param andCode:4];
    [_socket writeString:str];
}
-(void)websocketDidDisconnect:(JFRWebSocket*)socket error:(NSError*)error {
    NSLog(@"websocket is disconnected: %@",[error localizedDescription]);
     [WToast showWithText:@"断开连接"];
}
-(void)websocket:(JFRWebSocket *)socket didReceiveMessage:(NSString *)string{
    NSDictionary *dic =   [self StrtoJson:string];
    NSInteger types = [dic[@"code"]integerValue];
    NSLog(@".......收到消息........%ld",types);
    if(types==1||types==2||types==98){
        //消息和弹幕
        if(types==1||types==98){
            //系统消息
            Danmu_Model *model = [[Danmu_Model alloc]init];
            model.content = dic[@"data"][@"mes"];
            model.type = 0;
            [self.newsComent insertObject:model atIndex:0];
        }else if (types==2){
            Danmu_Model *model = [[Danmu_Model alloc]init];
          //  model.content =[NSString stringWithFormat:@"%@   %@",dic[@"data"][@"user_name"], dic[@"data"][@"mes"]];
            model.content =dic[@"data"][@"mes"];
            model.type = 1;
            model.userName = dic[@"data"][@"user_name"];
            NSInteger level = [dic[@"data"][@"groupid"]integerValue];
            NSString *imagestr = [NSString stringWithFormat:@"level%ld",level];
            NSTextAttachment* attach = [[NSTextAttachment alloc] init];
            UIImageView *imagess = [[UIImageView alloc]init];
            NSURL *urls = [NSURL URLWithString:dic[@"data"][@"group_logo"]];
      
            [attach setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:urls]]];
            NSAttributedString* attStr1 = [NSAttributedString attributedStringWithAttachment:attach];
            NSMutableAttributedString* attStr2 =[ [NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@" %@:",dic[@"data"][@"user_name"]]];
            UIColor *usernameColor = [XTool colorWithHexString:dic[@"data"][@"group_color"]];
            NSDictionary * secondAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:usernameColor,};
            [attStr2 setAttributes:secondAttributes range:NSMakeRange(0, attStr2.length)];
            NSMutableAttributedString* attStr = [[NSMutableAttributedString alloc] initWithAttributedString:attStr1];
             [attStr appendAttributedString:attStr2];
            [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@",model.content]]];
            attach.bounds = CGRectMake(0, -4, 30, 15);
            model.contentAttr = attStr;
              [self.newsComent insertObject:model atIndex:0];
      
        }else{
 
        }
        if(self.left_tab){
            [self.left_tab reloadData];
        }
    }else{
        //互动
        if(types==4){
            //互动开始
            self.cutdown_time = [dic[@"data"][@"current_endtime"]integerValue]-[dic[@"data"][@"service_time"]integerValue];
            if(self.isactiveing==1){
                [self handelActive];
            }else{
                self.isactiveing = 0;
                self.totalDaotime = 3;
                [self startDao];
            }
          //  [self handelActive];
        }else if (types==5){
            //互动结束
            self.isactiveing = 0;
            [self loadresult];
        }else if (types==96){
            self.endpopView.hidden = 0;
            [self.view bringSubviewToFront:self.endpopView];
            //   [self endpopView];
            
        }else if(types==6){
            UILabel *like_Num = (UILabel *)[self.view viewWithTag:1025];
           CGFloat praise =  [dic[@"data"][@"zan"]floatValue];
            if(praise>10000.00){
                CGFloat num  =  [dic[@"data"][@"zan"]floatValue]/10000;
                like_Num.text =[NSString stringWithFormat:@"%.2fw",num];
            }else{
                like_Num.text =[NSString stringWithFormat:@"%@", dic[@"data"][@"zan"]];
            }
            UILabel *guest = (UILabel *)[self.view viewWithTag:1026];
            guest.text = [NSString stringWithFormat:@"%@", dic[@"data"][@"online_number"]];
        }
    }
}




-(void)handelActive{
    self.activeStart = 1;
    NSInteger liveType = [self.live_Detail[@"live_type"]integerValue];
    UILabel *label = (UILabel *)[self.view viewWithTag:1028];
    label.textColor = PRICE_COLOR;
    label.text = @"抢购剩余时间";
 //   self.cutdown_time = [response[@"data"][@"current_endtime"]integerValue]-[response[@"data"][@"service_time"]integerValue];
    // [self showExamp];
    if(liveType==1){
        if(self.game_type==1){
            self.rewad_Num = [self.live_Detail[@"game"][@"right_num"]integerValue];
            [self startimer];//开启随机数字的模式
        }else if(self.game_type==2){
            [self showExamp];
        }
    }else{
        self.clickred = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickRed:)];
        [self.view addGestureRecognizer:self.clickred];
        [self startLoadDm];
    }
    self.isrobing = 1;
    
}
-(NSDictionary *)StrtoJson:(NSString *)jsonString{
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    return dic;
}
-(NSString *)dictiontoJson:(NSDictionary *)diction{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:diction
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}
-(NSString *)dictiontoJson:(NSDictionary *)diction andCode:(NSInteger)code{
    NSMutableString *str = [NSMutableString string];
    [str appendString:@"{"];
  
    [str appendString:@"\"code\":"];
    [str appendFormat:@"%ld,",(long)code];
//    [str appendString:@"{"];
    
    [str appendString:@"\"data\":"];
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:diction
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    [str appendString:jsonString];
    [str appendString:@"}"];
    return str;
}
#pragma mark 分享参数
-(void)ShareData{
   // http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live&ac=store&op=activity&m=bz_activities&token=194d7d75d1b6ac4ed794a53732af625e&ta=get_share_url
    NSDictionary *params = @{@"ctrl":@"live",
                             @"ac":@"store",
                             @"op":@"activity",
                             @"ta":@"get_share_url"};
    [self weqPostHandle:params success:^(id response) {
        if(response){
            self.shareData = response[@"data"];
        }
    } failure:^(NSError *error) {
        
    }];
}



-(void)loadAddress{
    NSDictionary *params = @{@"ctrl":@"live",
                             @"ac":@"member",
                             @"op":@"address",
                             @"ta":@"index"};
    [self weqPostHandle:params success:^(id response) {
        Regist2ViewController *vc = [[Regist2ViewController alloc]init];
        [self pushSecondVC:vc];

    } failure:^(NSError *error) {
        
    }];
}
-(NSString *)getMMSSFromSS:(NSInteger )totalTime{
    
    NSInteger seconds = totalTime;
    self.time_lab1.text = @"0";
    self.time_lab2.text = @"0";
    self.time_lab3.text = @"0";
    self.time_lab4.text = @"0";

    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    if(str_minute.length>1){
        self.time_lab1.text = [str_minute substringWithRange:NSMakeRange(0, 1)];
        self.time_lab2.text =  [str_minute substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.time_lab2.text = str_minute;
        self.time_lab1.text=@"0";
    }
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    if(str_second.length>1){
        self.time_lab3.text = [str_second substringWithRange:NSMakeRange(0, 1)];
        self.time_lab4.text =  [str_second substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.time_lab3.text = @"0";
        self.time_lab4.text = str_second;
    }
    
    // if(self.isrobing==1){
    
    self.time_lab1.backgroundColor = BUTTON_COLOR;
    self.time_lab2.backgroundColor = BUTTON_COLOR;
    self.time_lab4.backgroundColor = BUTTON_COLOR;
    self.time_lab3.backgroundColor = BUTTON_COLOR;
    
    //  }
    
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@分钟%@秒",str_minute,str_second];
    
    //  NSLog(@"format_time : %@",format_time);
    
    return format_time;
}
-(void)cacuTimes:(NSInteger )totalTime{
    if(totalTime==0){
        self.time_lab1.text = @"0";
        self.time_lab2.text =@"0";
        self.time_lab3.text = @"0";
        self.time_lab4.text = @"0";
        return;
    }
    NSInteger seconds = totalTime;
    NSInteger hour = seconds/3600;
    if(hour>0){
        self.dayLb.hidden= 0;
        self.dayLb.text = [NSString stringWithFormat:@"%ld小时",hour];
        
        UILabel *timedes = (UILabel *)[self.view viewWithTag:1028];
        timedes.frame = CGRectMake(timedes.frame.origin.x, screen_height-140, 100, 20);
        // self.dayLb = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-120, 100, 20)];
    }else{
        self.dayLb.hidden = 1;
    UILabel *timedes = (UILabel *)[self.view viewWithTag:1028];
        timedes.frame = CGRectMake(timedes.frame.origin.x, screen_height-120, 100, 20);
    }
    NSString *str_hour = [NSString stringWithFormat:@"%ld",seconds/3600];
    //format of minute
    NSInteger minute = (seconds%3600)/60;
    NSString *str_minute = [NSString stringWithFormat:@"%ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    //format of minute
    // NSString *str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    if(str_minute.length>1){
        self.time_lab1.text = [str_minute substringWithRange:NSMakeRange(0, 1)];
        self.time_lab2.text =  [str_minute substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.time_lab1.text = @"0";
        self.time_lab2.text = str_minute;
    }
    //format of second
    // NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    if(str_second.length>1){
        self.time_lab3.text = [str_second substringWithRange:NSMakeRange(0, 1)];
        self.time_lab4.text =  [str_second substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.time_lab3.text = @"0";
        self.time_lab4.text = str_second;
    }
    
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@分钟%@秒",str_minute,str_second];
    
    // NSLog(@"format_time : %@",format_time);
    
 //   return format_time;
}
- (void)endAnimation
{
    //  [self.timer invalidate];
    
    for (NSInteger i = 0; i < self.view.layer.sublayers.count ; i ++)
    {
        CALayer * layer = self.view.layer.sublayers[i];
        [layer removeAllAnimations];
    }
}


-(void)startLoadDm{
    //0.创建队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 0.4 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    
    //3.要调用的任务
    dispatch_source_set_event_handler(timer, ^{
        //  NSLog(@"DmGCD-----%@",[NSThread currentThread]);
        //   [self loadLikeNum];
        if(self.isclick==1){
            [self endAnimation];
            dispatch_cancel(timer);
            
        }else{
            [self showRain];
        }
        
    });
    
    //4.开始执行
    dispatch_resume(timer);
    
    //
    self.Dm_timer = timer;
}

//抢购倒计时
-(void)cutdown{
    __block  NSInteger start = 0;
    if(self.isrobing==1){
        start = self.end_time;
    }else{
        start = self.cutdown_time;
    }
     dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if(self.totalDaotime==0){
            self.activeOutLab.hidden = 1;
        }else{
            [self showActiveTimeout];
            self.totalDaotime--;
        }
        if(start<0){
            // dispatch_cancel(timer);
            if(self.isrobing==0){
                start = self.end_time;
                self.isrobing = 1;
                UILabel *label = (UILabel *)[self.view viewWithTag:1028];
                label.textColor = PRICE_COLOR;
                label.text = @"抢购剩余时间";
                self.dayLb.hidden = 1;
                label.frame = CGRectMake(label.frame.origin.x, screen_height-120, 100, 20);
              }else{
             [self stopTimer];
            dispatch_cancel(timer);
            }
            }else{
            [self getMMSSFromSS:start];
            start--;
            if(self.isrobing==0){
                self.end_time--;
            }
        }
    });
    
    //4.开始执行
    dispatch_resume(timer);
    
    //
    self.timer = timer;
    
}
#pragma mark 功能列表弹出框
-(void)openmorefunc{
    pop_func *pop = [[pop_func alloc]init];
    pop.delegate = self;
    [pop show:self.openDm Andcollect:self.collectStatus];
}
#pragma mark 功能点击事件
-(void)AlertView:(pop_func *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==0){
        //分享
        [self shareAction];
    }else if (buttonIndex==1){
        //举报
        ReportViewController *vc = [[ReportViewController alloc]init];
        NSDictionary *dic = self.live_Detail;
        vc.act_id  = self.live_id;
        vc.anchor_id = [NSString stringWithFormat:@"%@",dic[@"anchor_list"][0][@"anchor_id"]];
        [self pushSecondVC:vc];
    }else if (buttonIndex==2){
        //关闭弹幕
        [self opendDm];
    }else if(buttonIndex==3){
        //收藏直播间
        [self collect];
    }
}

#pragma mark 买商品的弹出框
-(void)showgoods{
    NSDictionary *diction= self.live_Detail[@"game"][0];
    Exam_popView *exam = [[Exam_popView alloc]initWithexamdata:diction];
    exam.delegate = self;
    [exam show];
}
-(void)AlertView:(Exam_popView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex andans:(NSInteger)ansindex andright:(BOOL)right{

    if(right==1){
        NSDictionary *param = @{@"ctrl":@"live",
                                @"ac":@"store",
                                @"op":@"activity",
                                @"ta":@"rob",
                                @"act_id":self.live_id};
        [self loadDm:param success:^(id response) {
            if(response){
                 [WToast showWithText:@"回答正确，请等待开奖"];
              }
        } failure:^(NSError *error) {
        }];
    }else{
        [WToast showWithText:@"回答错误，谢谢参与"];
    }
}
-(void)back{
    [WToast showWithText:@"直播已结束"];
    [self.navigationController popViewControllerAnimated:NO];
}
//获取活动的观看人数和点赞人数
-(void)loadLikeNum{

}
-(void)start_Live{
    [self initPlaySubViews];
}
#pragma mark 获取活动详情数据
-(void)loadliveInfo{
//    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
//    [self.view addSubview:_HUD];
//    _HUD.label.text = @"直播数据获取中";
//    //细节文字
//    _HUD.detailsLabel.text = @"请耐心等待";
//    //显示对话框
//    [_HUD showAnimated:YES];
    if(!self.Address_Id){
        self.Address_Id = @"";
    }
    NSDictionary *param = @{@"ctrl":@"live",
                            @"ac":@"store",
                            @"op":@"activity",
                            @"ta":@"detail",
                            @"id":self.live_id,
                            @"address_id":self.Address_Id};
    [self weqPostHandle:param success:^(id response) {
        NSLog(@"活动信息===%@",response);

        if(response){
            self.live_Detail = response[@"data"];
            self.playUrl = response[@"data"][@"bdlive"];
            self.isfans = [response[@"data"][@"anchor_list"][0][@"is_fans"]boolValue];
            self.game_type= [response[@"data"][@"game_type"]integerValue];//游戏类型，1位数字轮盘，2位知识竞赛，3为商品营销
            self.end_time =  [response[@"data"][@"end_time"]integerValue]-[response[@"data"][@"service_time"]integerValue];
            
            self.collectStatus = [response[@"data"][@"is_collect"]boolValue];
            [self start_Live];
            if([self.socket isConnected]==0){
            [self connectHost];//当开播时才连接socket
            }
            [self StartTime];
            }else{
                self.navigationController.interactivePopGestureRecognizer.enabled = YES;
                [self.navigationController popToRootViewControllerAnimated:1];
          }
    } failure:^(NSError *error) {

    } hasProgress:1];
}
#pragma mark 互动开始的倒计时
-(void)startDao{
     //[self showActiveTimeout];
  //  self.totalDaotime--;
    __block  NSInteger start = 0;
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    
    //3.要调用的任务
    dispatch_source_set_event_handler(timer, ^{
        if(self.totalDaotime>0){
            [self showActiveTimeout];
           // self.totalDaotime--;
          
        }else if(self.totalDaotime==0){
            self.activeOutLab.hidden = 1;
            [self handelActive];
            dispatch_cancel(self.timer1);
            
        }else{
            
           
        }
    });
    
    //4.开始执行
    dispatch_resume(timer);
    self.timer1 = timer;
}
#pragma mark 计时器获取弹幕和互动时间
-(void)StartTime{
    __block  NSInteger start = 0;
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //3.要调用的任务
    dispatch_source_set_event_handler(timer, ^{
        self.countHeart++;
        if(self.end_time==0){
            //直播结束
        dispatch_cancel(self.timer);
        }
        if(self.countHeart%10==0){
            NSDictionary *param = @{@"id":self.live_id,@"u_type":@"1",@"room_no":self.roomNum};
            NSString *str = [self dictiontoJson:param andCode:99];
            [self->_socket writeString:str];
          //  [self->_socket send:str];
        }
        if(self.isrobing==0){
            [self cacuTimes:self.end_time];
        }else{
        }
      
        if(self.cutdown_time>0){
            if(self.activeStart ==1){
            start = self.cutdown_time;
            }
        }
        self.end_time--;
        
        [self loadLikeNum];
       
        if(self.activeStart==0){
           
        }
        if(start<0){
            if(self.isrobing==1){
                self.activeStart=0;
                self.isclick = 1;
                self.isrobing = 0;
                [self stopTimer];
                self.dayLb.hidden= 0;
             
                UILabel *timedes = (UILabel *)[self.view viewWithTag:1028];
                timedes.text = @"距直播结束";
                timedes.textColor = [UIColor whiteColor];
                timedes.frame = CGRectMake(timedes.frame.origin.x, screen_height-140, 100, 20);
                
             //   [self loadresult];
            }
           }else{
            [self getMMSSFromSS:start];
            start--;
            self.cutdown_time--;
            if(self.isrobing==0){
                self.end_time--;
            }
        }
    });
    
    //4.开始执行
    dispatch_resume(timer);
    self.timer = timer;
}
#pragma mark 获取中奖结果

-(void)loadresult{
    [self.view endEditing:1];
    NSDictionary *params = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"whoprize",@"id":self.live_id};
    [self weqPostHandle:params success:^(id response) {
        //////NSLog(@"中奖结果==%@",response);
        if(response){
             [self.view endEditing:1];
            Result_popView *alert = [[Result_popView alloc]init];
            alert.delegate = self;
          ///////  NSLog(@"传递的参数......%@",response[@"data"]);
            [alert showWithData:response[@"data"] andisHost:0];
            NSArray *arr = response[@"data"];
            NSDictionary *userDic = [XTool GetDefaultInfo:USER_INFO];
            for(int i =0;i<arr.count;i++){
                if([userDic[@"token"]isEqualToString:arr[i][@"token"]]){
                NSDictionary *resultdic = arr[i];
                self.prize_Info = resultdic;
                }
             }

        }else{
            
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)AlertViews:(Result_popView *)alertViews clickedButtonAtIndex:(NSInteger)buttonIndex{
    RewardViewController *vc = [[RewardViewController alloc]init];
    vc.order_id = [NSString stringWithFormat:@"%@",self.prize_Info[@"orderid"]];
    vc.result_Order = self.prize_Info;
    [self pushSecondVC:vc];
}

-(void)dxAlertView:(DXAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    if(buttonIndex!=0){
        RewardViewController *vc = [[RewardViewController alloc]init];
        vc.order_id = [NSString stringWithFormat:@"%@",self.prize_Info[@"orderid"]];
        vc.result_Order = self.prize_Info;
        [self pushSecondVC:vc];
  //  }
}
-(void)pushtoError{
    NoRewardViewController *vc = [[NoRewardViewController alloc]init];
    [self pushSecondVC:vc];
}
-(void)pushtoRes{
    NSDictionary *userDic = [XTool GetDefaultInfo:USER_INFO];
    if([userDic[@"token"]isEqualToString:self.prize_token]){
        //中奖
        RewardViewController *vc = [[RewardViewController alloc]init];
        vc.order_id = [NSString stringWithFormat:@"%@",self.live_Detail[@"order_id"]];
        vc.result_Order = self.prize_Info;
        [self pushSecondVC:vc];
    }else{
        //未中奖
        NoRewardViewController *vc = [[NoRewardViewController alloc]init];
        [self pushSecondVC:vc];
    }
}
-(void)playStop:(NSNotification *)no{
    
}
-(void)homeExit:(NSNotification *)no{
    if(no.object){}
    else{
    if(self.socket){
        [self.socket disconnect];
                       }
        }
}
-(UIView *)lift_View{
    if(!_lift_View){
        int xleng = screen_width-150;
        int yleng = screen_height-150;
        int x =0 +  (arc4random() % xleng);
        int y =0 +  (arc4random() % yleng);
        _lift_View = [[UIView alloc]initWithFrame:CGRectMake(x, y, 200, 200)];
        //   _lift_View.backgroundColor = [UIColor redColor];
        [[[UIApplication sharedApplication]keyWindow ]addSubview:_lift_View];
        UIImageView *images = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];
        images.image = [UIImage imageNamed:@"礼物"];
        images.contentMode = UIViewContentModeScaleAspectFit;
        [_lift_View addSubview:images];
        
        UILabel *labe = [[UILabel alloc]initWithFrame:CGRectMake(0, 80, 200, 100)];
        labe.text = @"点击礼物";
        labe.textColor = [UIColor blackColor];
        labe.textAlignment = NSTextAlignmentCenter;
        [_lift_View addSubview:labe];
        UIButton *bn = [UIButton buttonWithType:UIButtonTypeCustom];
        bn.frame = CGRectMake(0, 0, 200, 200);
        [_lift_View addSubview:bn];
        [bn addTarget:self action:@selector(liftClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _lift_View;
}
-(void)liftClick{
    [self.lift_View removeFromSuperview];
    NSDictionary *param = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"rob",@"act_id":self.live_id};
    [self loadDm:param success:^(id response) {
        
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark
-(void)keyboardWillBeHiden:(NSNotification *)aNotification{
    self.danmuTextView.frame = CGRectMake(0, 10000, screen_width, 50);
}
#pragma mark 键盘弹出的响应事件

- (void)keyboardWillShow:(NSNotification *)aNotification {
    
    /* 获取键盘的高度 */
    NSDictionary *userInfo = aNotification.userInfo;
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = aValue.CGRectValue;
    /* 输入框上移 */
    CGFloat padding = 20;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:0.5f];
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    self.danmuTextView.frame = CGRectMake(0,screen_height-50-keyboardRect.size.height ,screen_width, 50);
    [UIView commitAnimations];
    [self.sendDanmutext becomeFirstResponder];
    
}


-(void)hideKb{
    [self.view endEditing:1];
}
//关闭直播界面
-(void)close_Live{
    [self.socket disconnect];
    [self.player pause];
    [self.player stop];
    [self.player reset];
    self.player = nil;
    dispatch_cancel(self.timer);
    self.timer = nil;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    [self.navigationController popToRootViewControllerAnimated:1];
}
//分享
-(void)shareAction{
    [LWShareService shared].shareBtnClickBlock = ^(NSIndexPath *index) {
        NSLog(@"%@",index);
        [self share:index.row];
    };
    [[LWShareService shared] showInViewController:self];

}
-(void)share:(NSInteger)type{
    [[LWShareService shared]hideSheetView];
        NSDictionary *dic = [XTool GetDefaultInfo:USER_INFO];
        NSString *codes = [NSString stringWithFormat:@"%@&invite=%@",self.shareData[@"url"] ,dic[@"invite_code"]];
        NSString *kLinkURL = codes;
        NSString *kLinkTitle =self.shareData[@"title"];
        NSString *kLinkDescription =self.shareData[@"title"];
       SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
        // 是否是文档
        req1.bText =  NO;
        //    WXSceneSession  = 0,        /**< 聊天界面    */
        //    WXSceneTimeline = 1,        /**< 朋友圈      */
        //    WXSceneFavorite = 2,
    if(type==0){
        req1.scene = WXSceneTimeline;
    }else{
        req1.scene = WXSceneSession;
    }
    
        //创建分享内容对象
        WXMediaMessage *urlMessage = [WXMediaMessage message];
        urlMessage.title = kLinkTitle;//分享标题
        urlMessage.description = kLinkDescription;//分享描述
        [urlMessage setThumbImage:[UIImage imageNamed:@"96.png"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
        //创建多媒体对象
        WXWebpageObject *webObj = [WXWebpageObject object];
        webObj.webpageUrl = kLinkURL;//分享链接
        //完成发送对象实例
        urlMessage.mediaObject = webObj;
        req1.message = urlMessage;
        //发送分享信息
        [WXApi sendReq:req1];
}
//点赞
-(void)like{
   NSDictionary *param = @{@"ctrl":@"live",
                            @"ac":@"store",
                            @"op":@"activity",
                            @"ta":@"zan",
                            @"act_id":self.live_id,
                            @"anchor_id":self.live_Detail[@"anchor_list"][0][@"anchor_id"],
                            @"store_id":self.live_Detail[@"sid"]};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            self.like_image.image = [UIImage imageNamed:@"009551"];
            [self praiseAnimation];
            NSDictionary *dic = @{@"room_no":self.roomNum};
            NSString *jsons = [self dictiontoJson:dic andCode:6];
            [self.socket writeString:jsons];
        }
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 收藏直播间
-(void)collect{
 if(self.collectStatus==0)
  {
    NSDictionary *param = @{@"ctrl":@"live",
                            @"ac":@"store",
                            @"op":@"activity",
                            @"ta":@"collect",
                            @"act_id":self.live_id,
                            @"anchor_id":self.live_Detail[@"anchor_list"][0][@"anchor_id"],
                            @"store_id":self.live_Detail[@"sid"]};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            [WToast showWithText:@"收藏成功"];
        }
    } failure:^(NSError *error) {
        
    }];
  }else{
//      http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live&ac=member&op=member&m=bz_activities&token=d6c58d58c38f023f92327383594aa192&ta=del_collect
//      NSDictionary *param = @{@"ctrl":@"live",@"ac":@"member",@"op":@"member",@"ta":@"del_collect",@"collect_id":[NSString stringWithFormat:@"%@",self.dataSouce[indexPath.row][@"fans_id"]]};
  }

}
#pragma mark 关注主播
-(void)focus:(UIButton *)sender{
    sender.selected = !sender.selected;
    if(self.isfans==1){
      NSDictionary *param = @{@"ctrl":@"live",@"ac":@"member",@"op":@"member",@"ta":@"del_atten",@"fans_id":[NSString stringWithFormat:@"%@",self.live_Detail[@"anchor_list"][0][@"anchor_id"]],@"anchor_id":[NSString stringWithFormat:@"%@",self.live_Detail[@"anchor_list"][0][@"anchor_id"]]};
        [self weqPostHandle:param success:^(id response) {
            if(response){
                [WToast showWithText:@"取消成功"];
                self.isfans = 0;
              
            }
        } failure:^(NSError *error) {
    
        }];
    
    }else{
    NSDictionary *param = @{@"ctrl":@"live",
                            @"ac":@"store",
                            @"op":@"activity",
                            @"ta":@"anchorlike",
                            @"act_id":self.live_id,
                            @"anchor_id":self.live_Detail[@"anchor_list"][0][@"anchor_id"]};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            [WToast showWithText:@"关注成功"];
             self.isfans = 1;
        }
    } failure:^(NSError *error) {
        
    }];
    }
}
#pragma mark 开启或者关闭弹幕
-(void)opendDm{
    self.openDm = !self.openDm;
    self.left_tab.hidden = !self.openDm;
}
#pragma mark - 点赞动画
- (void)praiseAnimation {
    
    UIImageView *imageView = [[UIImageView alloc] init];
    CGRect frame = self.view.frame;
    //  初始frame，即设置了动画的起点
    //imageView.frame = self.view.frame;
    imageView.frame = CGRectMake(frame.size.width - 40, frame.size.height - 120, 30, 30);
    //  初始化imageView透明度为0
    imageView.alpha = 0;
    imageView.backgroundColor = [UIColor clearColor];
    imageView.clipsToBounds = YES;
    //  用0.2秒的时间将imageView的透明度变成1.0，同时将其放大1.3倍，再缩放至1.1倍，这里参数根据需求设置
    [UIView animateWithDuration:0.2 animations:^{
        imageView.alpha = 1.0;
        imageView.frame = CGRectMake(frame.size.width - 40, frame.size.height - 120, 30, 30);
        imageView.layer.cornerRadius = 15;
        imageView.layer.masksToBounds = 1;
        int y =0 +  (arc4random() % self.color_Arr.count);
       NSString *imags = self.color_Arr[y];
        imageView.image = [UIImage imageNamed:imags];
        CGAffineTransform transfrom = CGAffineTransformMakeScale(1.3, 1.3);
        imageView.transform = CGAffineTransformScale(transfrom, 1, 1);
    }];
    [self.view addSubview:imageView];
    //  随机产生一个动画结束点的X值
    CGFloat finishX = frame.size.width - round(random() % 200);
    //  动画结束点的Y值
    CGFloat finishY = 200;
    //  imageView在运动过程中的缩放比例
    CGFloat scale = round(random() % 2) + 0.7;
    // 生成一个作为速度参数的随机数
    CGFloat speed = 1 / round(random() % 900) + 0.6;
    //  动画执行时间
    NSTimeInterval duration = 4 * speed;
    //  如果得到的时间是无穷大，就重新附一个值（这里要特别注意，请看下面的特别提醒）
    if (duration == INFINITY) duration = 2.412346;
    // 随机生成一个0~7的数，以便下面拼接图片名
    //  int imageName = round(random() % 8);
    //  开始动画
    [UIView beginAnimations:nil context:(__bridge void *_Nullable)(imageView)];
    //  设置动画时间
    [UIView setAnimationDuration:duration];
    //  设置imageView的结束frame
    imageView.frame = CGRectMake( finishX, finishY, 30 * scale, 30 * scale);
    
    //  设置渐渐消失的效果，这里的时间最好和动画时间一致
    [UIView animateWithDuration:duration animations:^{
        imageView.alpha = 0;
    }];
    
    //  结束动画，调用onAnimationComplete:finished:context:函数
    // [UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
    //  设置动画代理
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

#pragma mark 数字轮盘点击的事件
-(void)clickRandom:(UIButton *)btn{
    
    CGPoint centers = btn.center;
    [WaveView showInView:self.view center:centers];
    NSInteger rand_Nums = [btn.titleLabel.text integerValue];
    if(rand_Nums==self.rewad_Num){
        // [WToast showWithText:@"恭喜你中奖了"];
        NSDictionary *param = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"rob",@"act_id":self.live_id};
        [self loadDm:param success:^(id response) {
            
        } failure:^(NSError *error) {
            
        }];
    }
    
}
//
-(void)initallwaysVew{
    
}
#pragma mark 随机礼物
- (void)showRain
{
    UIImageView * imageV = [UIImageView new];
    NSArray *arr = @[@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物 copy",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物",@"礼物"];
    NSInteger count = arr.count;
    int y =0 +  (arc4random() % count );
    imageV.image = [UIImage imageNamed:arr[y]];
    imageV.contentMode = UIViewContentModeScaleAspectFit;
    imageV.frame = CGRectMake(0, 0, 44 , 44 );
    //  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickrain:)];
    self.moveLayer = [CALayer new];
    self.moveLayer.bounds = imageV.frame;
    self.moveLayer.anchorPoint = CGPointMake(0, 0);
    self.moveLayer.position = CGPointMake(0, -44 );
    self.moveLayer.contents = (id)imageV.image.CGImage;
    [self.view.layer addSublayer:self.moveLayer];
    [self addAnimation];
}
- (void)addAnimation
{
    CAKeyframeAnimation * moveAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    NSValue * A = [NSValue valueWithCGPoint:CGPointMake(arc4random() % 414, 0)];
    NSValue * B = [NSValue valueWithCGPoint:CGPointMake(arc4random() % 414, screen_height)];
    moveAnimation.values = @[A,B];
    moveAnimation.duration = arc4random() % 200 / 100.0 + 3.5;
    moveAnimation.repeatCount = 1;
    moveAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [self.moveLayer addAnimation:moveAnimation forKey:nil];
    
    CAKeyframeAnimation * tranAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    CATransform3D r0 = CATransform3DMakeRotation(M_PI/180 * (arc4random() % 360 ) , 0, 0, -1);
    CATransform3D r1 = CATransform3DMakeRotation(M_PI/180 * (arc4random() % 360 ) , 0, 0, -1);
    tranAnimation.values = @[[NSValue valueWithCATransform3D:r0],[NSValue valueWithCATransform3D:r1]];
    tranAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    tranAnimation.duration = arc4random() % 200 / 100.0 + 3.5;
    //为了避免旋转动画完成后再次回到初始状态。
    [tranAnimation setFillMode:kCAFillModeForwards];
    [tranAnimation setRemovedOnCompletion:NO];
    [self.moveLayer addAnimation:tranAnimation forKey:nil];
    
}
- (void)clickRed:(UITapGestureRecognizer *)sender
{
    [self.view endEditing:1];
    CGPoint point = [sender locationInView:self.view];
    for (int i = 0 ; i < self.view.layer.sublayers.count ; i ++)
    {
        CALayer * layer = self.view.layer.sublayers[i];
        if ([[layer presentationLayer] hitTest:point] != nil)
        {
            //  NSLog(@"%d",i);
            UIImageView * imageV = [UIImageView new];
            imageV.image = [UIImage imageNamed:@"礼物 copy"];
            imageV.contentMode = UIViewContentModeScaleAspectFit;
            imageV.frame = CGRectMake(0, 0, 44 , 44 );
            
            UIView * alertView = [UIView new];
            alertView.layer.cornerRadius = 5;
            alertView.frame = CGRectMake(point.x - 50, point.y, 100, 30);
            [self.view addSubview:alertView];
            UILabel * label = [UILabel new];
            label.font = [UIFont systemFontOfSize:17];
             [alertView addSubview:label];
            if(layer.contents==(id)imageV.image.CGImage){
                label.text =@"恭喜";
                 label.textColor = RGBA(255,223,14, 1);
                [self liftClick];
                self.isclick = 1;
                [WToast showWithText:@"您已点中礼物请等待开奖结果"];
                [self.view removeGestureRecognizer:self.clickred];
                return;
            }else{
                NSString * iString = @"继续加油";
                label.text = iString;
                 label.textColor = RGBA(255,223,14, 1);
                //                NSString * string = [NSString stringWithFormat:@"+%d金币",i];
               // NSString * iString = [NSString stringWithFormat:@"%d",i];
             //   NSMutableAttributedString * attributedStr = [[NSMutableAttributedString alloc]initWithString:iString];
                
//                [attributedStr addAttribute:NSFontAttributeName
//                                      value:[UIFont systemFontOfSize:27]
//                                      range:NSMakeRange(0, 1)];
//                [attributedStr addAttribute:NSFontAttributeName
//                                      value:[UIFont fontWithName:@"PingFangTC-Semibold" size:32]
//                                      range:NSMakeRange(1, iString.length)];
//                [attributedStr addAttribute:NSFontAttributeName
//                                      value:[UIFont systemFontOfSize:17]
//                                      range:NSMakeRange(1 + iString.length, 2)];
//                label.attributedText = attributedStr;
//                label.textColor = RGBA(255,223,14, 1);
                }
           
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(alertView.mas_centerX);
                make.centerY.equalTo(alertView.mas_centerY);
            }];
            
            [UIView animateWithDuration:1 animations:^{
                alertView.alpha = 0;
                alertView.frame = CGRectMake(point.x- 50, point.y - 100, 100, 30);
            } completion:^(BOOL finished) {
                [alertView removeFromSuperview];
            }];
            
            
        }
    }
}
-(void)randoms{
    int y =0 +  (arc4random() % 10);
    [self.random_Btn setTitle:[NSString stringWithFormat:@"%d",y] forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 界面UI处理
-(void)initPlaySubViews{
   #pragma mark 播放器初始化以及设置
    self.player = [[BDCloudMediaPlayerController alloc] initWithContentURL:[NSURL URLWithString:self.playUrl]];
    self.player.view.backgroundColor = RGBA(200, 200, 200, .8);
    [self.player setScalingMode:BDCloudMediaPlayerScalingModeFill];
    [BDCloudMediaPlayerController setLogReport:1];
    [self.player setPlaybackVolume:1];
    [self.player setPauseInBackground:1];

    [self.player enableAutoIdleTimerDisabled:YES];//播放时常亮设置
   #pragma mark 绑定顶部主播信息元素
    NSInteger margin_Top = KISIphoneX?55:30;
    [self bindHostInfo];
    #pragma mark 底部规则覆盖层
    UIView *botom_View = [[UIView alloc]initWithFrame:CGRectMake(0, screen_height-50, screen_width, 50)];
    botom_View.backgroundColor = RGBA(0, 0, 0, .3);
    UILabel *rule_Lab = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, 0, screen_width-70, 50)];
    rule_Lab.textColor = [UIColor whiteColor];
    rule_Lab.text =@"本场规则：在随机变化的数字中，最先点中5";
    rule_Lab.font = [UIFont systemFontOfSize:13];
    rule_Lab.tag = 10288;
    rule_Lab.numberOfLines = 2;
    [botom_View addSubview:rule_Lab];
    
    NSInteger live_type = [self.live_Detail[@"live_type"]integerValue];
    if(live_type==1){
        if(self.game_type==1){
            self.rewad_Num = [self.live_Detail[@"game"][@"right_num"]integerValue];
            rule_Lab.text =[NSString stringWithFormat:@"本场规则：在随机变化的数字中，最先点中%ld",(long)self.rewad_Num];
        }else{
            rule_Lab.text =@"本场规则：最先答对题目的人可中奖";
        }
    }else{
        rule_Lab.text =@"本场规则：在随机的礼物中最先点到中奖礼物的可中奖";
    }
    
    UIImageView *guest_NumImage = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-60, 19, 12, 12)];
    guest_NumImage.image = [UIImage imageNamed:@"007551"];
    [botom_View addSubview:guest_NumImage];
    
    UILabel *guest_Num = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-40, 0, 50, 50)];
    guest_Num.textColor = [UIColor whiteColor];
    guest_Num.text = @"0";
    guest_Num.font= [UIFont systemFontOfSize:12];
    [botom_View addSubview:guest_Num];
    guest_Num.tag = 1026;
    [self.player.view addSubview:botom_View];
    #pragma mark 直播倒计时元素
    UILabel *time_text = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-120, 100, 20)];
    time_text.text = @"距直播结束";
    time_text.textColor = [UIColor whiteColor];
    time_text.font = [UIFont systemFontOfSize:15];
    time_text.tag = 1028;
    [self.player.view addSubview:time_text];
    
    self.dayLb = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-115, 110, 20)];
    self.dayLb.textColor = [UIColor whiteColor];
    self.dayLb.text = @"0";
    // self.dayLb.backgroundColor = BUTTON_COLOR;
    self.dayLb.font = [UIFont systemFontOfSize:18];
    self.dayLb.textAlignment = 1;
    self.dayLb.layer.cornerRadius = 5;
    self.dayLb.textAlignment = NSTextAlignmentLeft;
    self.dayLb.layer.masksToBounds = 1;
    [self.player.view addSubview:self.dayLb];
    self.dayLb.hidden = 1;
    
    self.time_lab1 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-90,
                                                              time_Lab_width, time_Lab_height)];
    self.time_lab1.textColor = [UIColor blackColor];
    self.time_lab1.text = @"0";
    self.time_lab1.backgroundColor = RGBA(0, 0, 0, .5);
    self.time_lab1.font = [UIFont systemFontOfSize:20];
    self.time_lab1.textAlignment = 1;
    self.time_lab1.layer.cornerRadius = 5;
    self.time_lab1.layer.masksToBounds = 1;
    [self.player.view addSubview:self.time_lab1];
    
    self.time_lab2 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width+10-5,
                                                              screen_height-90, time_Lab_width, time_Lab_height)];
    self.time_lab2.textColor = [UIColor blackColor];
    self.time_lab2.text = @"0";
    self.time_lab2.backgroundColor = RGBA(0, 0, 0, .5);
    self.time_lab2.font = [UIFont systemFontOfSize:20];
    self.time_lab2.textAlignment = 1;
    self.time_lab2.layer.cornerRadius = 5;
    self.time_lab2.layer.masksToBounds = 1;
    [self.player.view addSubview:self.time_lab2];
    
    UILabel *mao = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*2+10,
                                                            screen_height-90, 5, time_Lab_height)];
    mao.text = @":";
    mao.textColor = [UIColor blackColor];
    mao.font = [UIFont systemFontOfSize:20];
    [self.player.view addSubview:mao];
    
    self.time_lab3 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*2+20, screen_height-90,
                                                              time_Lab_width, time_Lab_height)];
    self.time_lab3.textColor = [UIColor blackColor];
    self.time_lab3.text = @"0";
    self.time_lab3.backgroundColor = RGBA(0, 0, 0, .5);
    self.time_lab3.font = [UIFont systemFontOfSize:20];
    self.time_lab3.textAlignment = 1;
    self.time_lab3.layer.cornerRadius = 5;
    self.time_lab3.layer.masksToBounds = 1;
    [self.player.view addSubview:self.time_lab3];
    
    self.time_lab4 = [[UILabel alloc]initWithFrame:
    CGRectMake(margin_left+time_Lab_width*3+30-5, screen_height-90,
    time_Lab_width, time_Lab_height)];
    self.time_lab4.textColor = [UIColor blackColor];
    self.time_lab4.text = @"0";
    self.time_lab4.backgroundColor = RGBA(0, 0, 0, .5);
    self.time_lab4.font = [UIFont systemFontOfSize:20];
    self.time_lab4.textAlignment = 1;
    self.time_lab4.layer.cornerRadius = 5;
    self.time_lab4.layer.masksToBounds = 1;
    [self.player.view addSubview:self.time_lab4];
    #pragma mark 发送弹幕触发元素
    UITextField *DanmuText = [[UITextField alloc]initWithFrame:
    CGRectMake(margin_left+time_Lab_width*3+30-5+30, screen_height-100,
    screen_width-(margin_left+time_Lab_width*3+30-5+30)-120, 40)];
    DanmuText.layer.cornerRadius = 20;
    DanmuText.layer.masksToBounds = 1;
    DanmuText.font = [UIFont systemFontOfSize:15];
    DanmuText.backgroundColor= RGBA(0, 0, 0, .2);
    DanmuText.placeholder = @" 发送弹幕";
    DanmuText.delegate = self;
    [DanmuText setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.player.view addSubview:DanmuText];
    #pragma mark 右边的点赞元素

    UIButton *dianzan = [UIButton buttonWithType:UIButtonTypeCustom];
    dianzan.frame = CGRectMake(screen_width-50, screen_height-100, 40, 40);
    [dianzan setImage:[UIImage imageNamed:@"praise1"] forState:UIControlStateNormal];
    [dianzan addTarget:self action:@selector(like) forControlEvents:UIControlEventTouchUpInside];
    // share_Btn.backgroundColor = [UIColor redColor];
    //[share_Btn setBackgroundImage:[UIImage imageNamed:@"分享按钮551"] forState:UIControlStateNormal];
    [self.player.view addSubview:dianzan];
    //点赞数
    UILabel *likeNum = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-50, screen_height-125, 40, 18)];
    likeNum.font = [UIFont systemFontOfSize:13];
    likeNum.textColor = BUTTON_COLOR;
    likeNum.backgroundColor = [UIColor redColor];
    likeNum.layer.cornerRadius = 9;
    likeNum.layer.masksToBounds = 1;
    likeNum.tag = 1025;
    likeNum.textAlignment = NSTextAlignmentCenter;
    [self.player.view addSubview:likeNum];
    
    self.like_image = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-160, 30, 30)];
    self.like_image.contentMode = UIViewContentModeScaleAspectFit;
    self.like_image.image = [UIImage imageNamed:@"礼物"];
    
    UIButton *like_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    like_Btn.frame = CGRectMake(screen_width-50, screen_height-160, 40, 40);
    [like_Btn setImage:[UIImage imageNamed:@"礼物"] forState:UIControlStateNormal];
    [like_Btn addTarget:self action:@selector(showgoods) forControlEvents:UIControlEventTouchUpInside];
    like_Btn.tag = 2888;
    like_Btn.hidden = 1;
    [self.player.view addSubview:like_Btn];
    #pragma mark 商家logo
    UIImageView *storeIcon = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-100, screen_height-100, 40, 40)];
    storeIcon.contentMode = UIViewContentModeScaleAspectFill;
    NSURL *storeUrl = [NSURL URLWithString:self.live_Detail[@"store"][@"logo"]];
    [ storeIcon sd_setImageWithURL:storeUrl placeholderImage:[UIImage imageNamed:@"96"]];
    storeIcon.layer.cornerRadius = 20;
    storeIcon.layer.masksToBounds = 1;
    [self.player.view addSubview:storeIcon];
    #pragma mark 随机数抽奖元素
    self.randImg = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width/2-50, screen_height/2-100, 100, 100)];
    [self.randImg setImage:[UIImage imageNamed:@"random"]];
    [self.player.view addSubview:self.randImg];
    self.randImg.hidden = 1;
    self.random_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.random_Btn.frame = CGRectMake(screen_width/2-50, screen_height/2-100, 100, 100);
    [self.random_Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.random_Btn setTitle:@"8" forState:UIControlStateNormal];
    self.random_Btn.titleLabel.font = [UIFont systemFontOfSize:60];
    self.random_Btn.layer.cornerRadius = 50;
    self.random_Btn.layer.masksToBounds = 1;
    [self.random_Btn addTarget:self action:@selector(clickRandom:) forControlEvents:UIControlEventTouchUpInside];
    self.random_Btn.hidden = 1;
    #pragma mark 开奖结果
    self.result_view = [[UIView alloc]initWithFrame:CGRectMake(screen_width/2-80, screen_height/2-80, 160, 160)];
    self.result_view.backgroundColor = RGBA(208, 29, 27, .3);
    [self.player.view addSubview:self.result_view];
    self.result_view.hidden = 1;
    UILabel *titles = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, 160, 20)];
    titles.textAlignment =  1;
    titles.text = @"恭喜";
    titles.textColor = [UIColor whiteColor];
    titles.font = [UIFont systemFontOfSize:14];
    [self.result_view addSubview:titles];
    
    UILabel *titles1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 120, 160, 20)];
    titles1.textAlignment =  1;
    titles1.text = @"中奖";
    titles1.textColor = [UIColor whiteColor];
    titles1.font = [UIFont systemFontOfSize:14];
    [self.result_view addSubview:titles1];
    #pragma mark 右上角关闭按钮
   UIButton *close_btn = [UIButton buttonWithType:UIButtonTypeCustom];
    close_btn.frame = CGRectMake(screen_width-50, margin_Top+2, 35, 35);//closeed.png
    [close_btn setImage:[UIImage imageNamed:@"closeed.png"] forState:UIControlStateNormal];
    [close_btn addTarget:self action:@selector(close_Live) forControlEvents:UIControlEventTouchUpInside];
    [self.player.view addSubview:close_btn];
    #pragma mark 右上角更多功能按钮
    UIButton *share_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    share_Btn.frame = CGRectMake(screen_width-100, margin_Top+2, 35, 35);
    [share_Btn setImage:[UIImage imageNamed:@"Group 4 Copy 2"] forState:UIControlStateNormal];
    [share_Btn addTarget:self action:@selector(openmorefunc) forControlEvents:UIControlEventTouchUpInside];
    [self.player.view addSubview:share_Btn];
    #pragma mark 将播放器的view元素j添加到主页面上，弹幕和抽奖元素放在最上层
    [self.view addSubview:self.player.view];
    self.player.shouldAutoplay = YES;
    [self.player prepareToPlay];
    self.player.view.backgroundColor = [UIColor clearColor];
    [self left_tab];
    [self.player.view insertSubview:self.random_Btn atIndex:1000];
}
#pragma mark 懒加载的UI元素和数据
-(UILabel *)activeOutLab{
    if(!_activeOutLab){
        _activeOutLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height)];
        _activeOutLab.textAlignment= NSTextAlignmentCenter;
        _activeOutLab.textColor = [UIColor redColor];
        _activeOutLab.font = [UIFont systemFontOfSize:20];
        [self.view addSubview:_activeOutLab];
    }
    return _activeOutLab;
}
-(NSArray *)color_Arr{
    if(!_color_Arr){
        _color_Arr = @[@"Mask Copy 3",@"Mask Copy 4",@"Mask Copy 5",@"Mask Copy 6",@"Mask Copy 7",@"Mask Copy 8",@"Mask Copy 9"];
    }
    return _color_Arr;
}
-(UITableView *)left_tab{
    if(!_left_tab){
        _left_tab = [[UITableView alloc]initWithFrame:CGRectMake(0, screen_height-360, screen_width, 200) style:UITableViewStylePlain];
        _left_tab.delegate = self;
        _left_tab.dataSource = self;
        _left_tab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _left_tab.transform = CGAffineTransformMakeScale(1, -1);//翻转180
        _left_tab.backgroundColor = [UIColor clearColor];
        _left_tab.showsVerticalScrollIndicator = 0;
        [self.player.view addSubview:_left_tab];
        [self.view bringSubviewToFront:_left_tab];
    }
    return _left_tab;
}
-(UIView *)danmuTextView{
    if(!_danmuTextView){
        _danmuTextView = [[UIView alloc]initWithFrame:CGRectMake(0, 1000, screen_width, 50)];
        _danmuTextView.backgroundColor = RGB(225, 225, 225);
        [_danmuTextView addSubview:self.sendDanmutext];
        UIButton *send_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
        send_Btn.frame = CGRectMake(screen_width-60, 0, 60, 50);
        [send_Btn setTitle:@"发送" forState:UIControlStateNormal];
        [send_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        send_Btn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_danmuTextView addSubview:send_Btn];
        [send_Btn addTarget:self action:@selector(senDamu) forControlEvents:UIControlEventTouchUpInside];
        [self.player.view addSubview:_danmuTextView];
    }
    return _danmuTextView;
}
-(UITextField *)sendDanmutext{
    if(!_sendDanmutext){
        _sendDanmutext = [[UITextField alloc]initWithFrame:CGRectMake(10, 5, screen_width-70, 40)];
        _sendDanmutext.placeholder = @"发送弹幕,长度小于20";
        _sendDanmutext.layer.cornerRadius = 20;
        _sendDanmutext.delegate  = self;
       [_sendDanmutext setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
        _sendDanmutext.layer.masksToBounds = 1;
        _sendDanmutext.font = [UIFont systemFontOfSize:14];
        _sendDanmutext.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
        _sendDanmutext.leftViewMode = UITextFieldViewModeAlways;
        _sendDanmutext.backgroundColor = [UIColor whiteColor];
    }
    return _sendDanmutext;
}
#pragma mark 直播间i结束时的覆盖层
-(UIView *)endpopView{
    if(!_endpopView){
        _endpopView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height)];
        _endpopView.backgroundColor = RGBA(0, 0, 0, 0.5);
        UILabel *labe = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, screen_width, 100)];
        labe.center = self.view.center;
        labe.textColor = BUTTON_COLOR;
        labe.textAlignment = NSTextAlignmentCenter;
        labe.font = [UIFont systemFontOfSize:30];
        labe.text = @"直播已结束";
        CGPoint centerPoint = self.view.center;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 150, 40);
        btn.backgroundColor = BUTTON_COLOR;
        [btn setTitle:@"退出直播间" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.layer.cornerRadius = 20;
        btn.center = CGPointMake(centerPoint.x, centerPoint.y+50);
        [btn addTarget:self action:@selector(close_Live) forControlEvents:UIControlEventTouchUpInside];
        [_endpopView addSubview:btn];
        [_endpopView addSubview:labe];
        [self.view addSubview:_endpopView];
        _endpopView.hidden = 1;
        // [self.view addSubview:labe];
    }
    return _endpopView;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
